package org.sheep.world;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

import org.sheep.R;
import org.sheep.world.tile.Tile;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.util.Log;

public class WorldMapFactory {
	private String file = null;
	private int width;
	private int height;
	private Context context;

	// default WorldMap containing only grass
	public WorldMapFactory(int width, int height, Context context) {
		this.width = width;
    this.height = height;
    this.context = context;
  }

	// build WorldMap from File
	public WorldMapFactory(int width, int height, Context context, String file) {
    this(width, height, context);
		this.file = file;
		
		//add other tiles
	}

	public WorldMap build() throws XmlPullParserException, IOException {
	  //the SuppressWarnings annotation was choosen because of an JavaGenerics Bug
		@SuppressWarnings("unchecked")
    LinkedList<Tile>[] map = new LinkedList[width];
    WorldMap wMap = new WorldMap();
      
		if (file == null)
			for (int x = 0; x < width; x++) {
				map[x] = new LinkedList<Tile>();
			  for (int y = 0; y < height; y++) {
					map[x].add(wMap.tiles[0]);
				}
			}
		else {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new InputStreamReader(new FileInputStream(file)));
			int eventType = xpp.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_DOCUMENT) {
					Log.i("WorldMapFactory", "Start document");
				} else if (eventType == XmlPullParser.START_TAG) {
					Log.i("WorldMapFactory", "Start tag " + xpp.getName());
				} else if (eventType == XmlPullParser.END_TAG) {
					Log.i("WorldMapFactory", "End tag " + xpp.getName());
				} else if (eventType == XmlPullParser.TEXT) {
					Log.i("WorldMapFactory", "Text " + xpp.getText());
				}
				eventType = xpp.next();
			}
		}
		
		wMap.setMap(map);
		return wMap;
	}
}
